﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Entity;
using DAL;

namespace Project_V1
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            this.Load += FrmMain_Load;
            this.timer1.Interval = 200;
        }

        private FastenerService objFastenerService = new FastenerService();
        private LayerStackService objLayerStackService = new LayerStackService();
        //为了使用下拉框选择工艺规范,先读取工艺规范信息
        private SettingsService objSettingsService = new SettingsService();

        #region 主窗体Load事件,可添加关闭窗体相关方法
        void FrmMain_Load(object sender, EventArgs e)
        {
            if (Beckhoff_PLC.CreateHandle())
            {
                Beckhoff_PLC.t.Start();//开启线程,开启CommThread类内的读写方法的线程
                this.btnConn.BackColor = Color.FromArgb(60, 179, 113);//主页按钮显示通讯成功
            }
            else
            {
                this.btnConn.BackColor = System.Drawing.SystemColors.ControlLight;               
            }
            InitializeList();//从数据库读取工艺规范集合,后续可以简化为从本地XML文件读取
            InitialTxt();//初始化配置文件信息,存入集合

            AlarmHanlder.AlarmThreadStart();//打开报警处理20240314


            this.btn_View_Click(null, null); //显示的初始界面设为为FrmView
            this.timer1.Enabled = true;
        }
        #endregion

        #region 初始化集合信息,读取工艺规范集合,下拉框可选择工艺规范
        private void InitializeList()
        {
            CommonMethods.SettingsList= objSettingsService.GetAll();
            CommonMethods.FastenerList = objFastenerService.GetAll();
            CommonMethods.LayerStackList = objLayerStackService.GetAll();
        }
        #endregion

        #region 从xml文件读取信息存入集合VarAdsList,遍历集合,初始化字典集合赋空值
        private void InitialTxt()
        {
            //从xml文件读取变量集合信息
            CommonMethods.VarAdsList = CommonMethods.LoadXML(CommonMethods.VarFilePath);
            //字典集合CurrentValue添加变量名,空值
            foreach (Variable_Ads item in CommonMethods.VarAdsList)
            {
                if (!CommonMethods.CurrentValue.ContainsKey(item.VarName))
                {
                    CommonMethods.CurrentValue.Add(item.VarName, "");
                }

                if (!CommonMethods.CurrentType.ContainsKey(item.VarName))
                {
                    CommonMethods.CurrentType.Add(item.VarName, item.DataType);
                }

                if (!CommonMethods.CurrentName.ContainsKey(item.VarName))
                {
                    CommonMethods.CurrentName.Add(item.VarName, item.VarName);
                }

                

            }
        }
        #endregion
        
        #region 打开关闭窗体操作
        private void OpenWindow(Form Frm)
        {
            Frm.TopLevel = false;
            Frm.FormBorderStyle = FormBorderStyle.None;
            Frm.Dock = DockStyle.Fill;
            Frm.Parent = this.MainPanel;
            Frm.Show();
            Frm.TopMost = false;

        }
        private bool CloseWindow(string FrmName)//关闭主窗体内多余的Form
        {
            foreach (Control ct in this.MainPanel.Controls)
            {
                if (ct is Form)
                {
                    Form Frm = (Form)ct;
                    if (Frm.Name == FrmName)
                    {
                        return true;
                    }
                    else
                    {
                        Frm.Close();
                    }
                }
            }
            return false;
        }


        public static void FrmMaintenanceUIButtonFalse()
        {
            Beckhoff_PLC.WriteVariable(".btMotorDebug", false);
            Beckhoff_PLC.WriteVariable(".btFeedTest", false);
        }

        private void btn_View_Click(object sender, EventArgs e)
        {
            if (CloseWindow("FrmView") == false)
            {
                OpenWindow(new FrmView());
                this.lbl_Title.Text = sender == null ? " 控制流程" : ((Button)sender).Tag.ToString();
                BackColorSet(sender == null ? " 控制流程" : ((Button)sender).Tag.ToString());

                Beckhoff_PLC.WriteVariable(".btMotorDebug", false); 
                Beckhoff_PLC.WriteVariable(".btFeedTest", false);

                FrmMaintenanceUIButtonFalse();
            }
        }

        private void btn_ParamSet_Click(object sender, EventArgs e)
        {
             
            using (FrmLcok objFrm = new FrmLcok())
            {
                if (objFrm.ShowDialog() == DialogResult.OK) // 检查对话框的返回值
                {
                    if (CloseWindow("FrmMaintenance") == false)
                    {
                        OpenWindow(new FrmMaintenance());
                        this.lbl_Title.Text = " " + ((Button)sender).Tag.ToString();
                        BackColorSet(((Button)sender).Tag.ToString());
                    }
                }
            }




            //if (CloseWindow("FrmMaintenance") == false)
            //{
            //    OpenWindow(new FrmMaintenance());
            //    this.lbl_Title.Text = " " + ((Button)sender).Tag.ToString();
            //    BackColorSet(((Button)sender).Tag.ToString());
            //}
        }

        private void btn_Alarm_Click(object sender, EventArgs e)
        {
            if (CloseWindow("FrmAlarm") == false)
            {
                OpenWindow(new FrmAlarm());
                this.lbl_Title.Text = " " + ((Button)sender).Tag.ToString();
                BackColorSet(((Button)sender).Tag.ToString());
                FrmMaintenanceUIButtonFalse();
            }
        }

        private void btn_HardwareConfig_Click(object sender, EventArgs e)
        {
            if (CloseWindow("FrmProcessConfig") == false)
            {
                OpenWindow(new FrmProcessConfig());
                this.lbl_Title.Text = " " + ((Button)sender).Tag.ToString();
                BackColorSet(((Button)sender).Tag.ToString());
                FrmMaintenanceUIButtonFalse();
            }
        }

        private void btn_Report_Click(object sender, EventArgs e)
        {
            if (CloseWindow("FrmHistory") == false)
            {
                OpenWindow(new FrmHistory());
                this.lbl_Title.Text = " " + ((Button)sender).Tag.ToString();
                BackColorSet(((Button)sender).Tag.ToString());
                FrmMaintenanceUIButtonFalse();
            }
        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void BackColorSet(string item)
        {
            this.btn_View.BackColor = Color.WhiteSmoke;
            this.btn_ParamSet.BackColor = Color.WhiteSmoke;
            this.btn_Alarm.BackColor = Color.WhiteSmoke;
            this.btn_Report.BackColor = Color.WhiteSmoke;
            this.btn_HardwareConfig.BackColor = Color.WhiteSmoke;
            switch (item)
            {
                case "控制流程":
                    this.btn_View.BackColor = Color.FromArgb(60, 179, 113);
                    break;
                case "设备调试":
                    this.btn_ParamSet.BackColor = Color.FromArgb(60, 179, 113);
                    break;
                case "工艺规范":
                    this.btn_HardwareConfig.BackColor = Color.FromArgb(60, 179, 113);
                    break;
                case "数据报表":
                    this.btn_Report.BackColor = Color.FromArgb(60, 179, 113);
                    break;
                case "SysAlarmActive":
                    this.btn_Alarm.BackColor = Color.FromArgb(60, 179, 113);
                    break;
                default:
                    this.btn_View.BackColor = Color.FromArgb(60, 179, 113);
                    break;
            }
        }


        #endregion

        private void timer1_Tick(object sender, EventArgs e)
        {
            foreach (Control ct in this.BottomPanel.Controls)//遍历BottomPanel内控件,并赋值
            {
                if (ct is Button && ct.Tag != null && ct.Tag.ToString() != "" && ct.Tag.ToString().IndexOf(".") != -1)
                {
                    if (CommonMethods.CurrentValue[ct.Tag.ToString()] == "True" && CommonMethods.CurrentValue.ContainsKey(ct.Tag.ToString()))
                    {
                        ct.BackColor = Color.FromArgb(60, 179, 113);



                    }
                    else
                    {
                        ct.BackColor = Color.FromArgb(255, 255, 255);
                    }
                }
            }

            if (AlarmHanlder.alarmStr != "")
            {
                //btn_Alarm.BackColor = Color.Red;// Color.FromArgb(60, 179, 113); 
                //lbl_status.Text = AlarmHanlder.alarmNewStr;  

            }
            else
            {

                //btn_Alarm.BackColor = Color.White;
            }

        }

        private void lbl_Title_Click(object sender, EventArgs e)
        {

        }

        private void MainPanel_Paint(object sender, PaintEventArgs e)
        {

        }

        private void btn_AutoMode_Click(object sender, EventArgs e)
        {
           // FrmMaintenanceUIButtonFalse();
        }

        private void btn_Debugmode_Click(object sender, EventArgs e)
        {
           // FrmMaintenanceUIButtonFalse();
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
           // FrmMaintenanceUIButtonFalse();
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            //FrmMaintenanceUIButtonFalse();
        }

        private void btn_FormMin_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void timer2_Tick(object sender, EventArgs e)
        {

            try
            {
                string sql = "Select top(1)  CONVERT(varchar(100),InsertTime,20) as InsertTime,CONVERT(varchar(100),EndTime,20) as EndTime,VarName,AlarmState,Priority,AlarmType,iif( Value = 'True',N'开始报警',N'结束报警') as Value,AlarmValue,Operator,Note from AlarmData where 1=1 and Value = 'True'  and Category in( '警告类' ,'故障类') order by InsertTime desc";
                DataTable dt = new DataTable();
                dt = SQLHelper.GetDataSet(sql).Tables[0];

                if (dt.Rows.Count > 0)
                {
                    lbl_status.Text = dt.Rows[0][0].ToString() + ":" + dt.Rows[0][5].ToString();

                    if (lbl_status.Text.IndexOf("故障") != -1)
                    {
                        lbl_status.ForeColor = Color.Red;
                    }

                    if (lbl_status.Text.IndexOf("不成功") != -1 ||
                        lbl_status.Text.IndexOf("硬限位") != -1)
                    {
                        lbl_status.ForeColor = Color.Yellow;
                    }


                    if (lbl_status.Text.IndexOf("已上电") != -1 ||
                        lbl_status.Text.IndexOf("已准备") != -1 ||
                        lbl_status.Text.IndexOf("已使能") != -1 ||
                        lbl_status.Text.IndexOf("模式中") != -1 ||
                        lbl_status.Text.IndexOf("测试中") != -1 ||
                        lbl_status.Text.IndexOf("已按下") != -1 ||
                        lbl_status.Text.IndexOf("已达到") != -1 ||
                        lbl_status.Text.IndexOf("进行中") != -1 ||
                        lbl_status.Text.IndexOf("停止中") != -1 ||
                        (lbl_status.Text.IndexOf("成功") != -1 && lbl_status.Text.IndexOf("不成功") == -1) ||
                        lbl_status.Text.IndexOf("判断") != -1 ||
                        lbl_status.Text.IndexOf("调试中") != -1


                        )
                    {
                        lbl_status.ForeColor = Color.Green;
                    }
                }
                else
                {

                    lbl_status.Text = "";
                }
            }
            catch
            {


            }



        }
    }
}
